import asyncio
import json
import logging
from typing import Any

from fastmcp import Client
SERVER_URLS = ["http://127.0.0.1:19970/sse/"]

success_code = 200
error_code = 500
def  common_result(status:int=success_code,data:Any=None,message:str="") -> json:
    """通用返回
    Args:
        status: 状态码, 200正常返回. 500失败
        data: 返回数据
        message: 返回信息
        """
    return {"status": status, "data": data, "message": message}

async def get_single_tools(url:str) ->json:
    """获取单个mcp server的api接口"""
    try:
        client = Client(url)
        async with client:
            if client is None:
                return []
            #拿到所有api
            mcp_tools = await client.list_tools()
            function_calling_tools = []
            #组装成function calling
            for tool in mcp_tools:
                function_tool = {
                    "type": "function",
                    "function": {
                        "name": f"{tool.name}&&{url}",
                        "description": str(tool.description),  # 描述
                        "parameters": tool.inputSchema
                    }
                }
                function_calling_tools.append(function_tool)
            await client.close()
            return common_result(data=function_calling_tools)
    except Exception as e:
        return common_result(status=error_code, message=str(e))



async def get_tools() ->list[str]:
    """获取所有mcp server的接口列表
    Returns:接口列表
    """
    tools = []
    for url in SERVER_URLS:
        result = await get_single_tools(url)
        if result["status"] == success_code:
            for data in result["data"]:
                tools.append(data)
        else:
            logging.log(logging.ERROR, f"'{url}'获取tools失败,{result["message"]}")
    return tools


#调用工具
async def get_tool(content) -> list[str]:
    #TODO: 不懂能否从function calling中获取到url,还需尝试
    if content is not None:
        client = Client("")
        result = []
        async with client:
            if client is None:
                return []
            print(content)
            #{'role': 'assistant', 'reasoning_content': '', 'content': None, 'tool_calls': [{'type': 'function', 'function': {'name': '', 'arguments': '{}'}, 'id': ''}]}
            content_json = content
            if "tool_calls" in content_json and len(content_json["tool_calls"]) > 0:
                # 调用工具
                server_result = None
                """调用工具"""
                tool_calls = content_json["tool_calls"]
                for tool_call in tool_calls:
                    function_name = str(tool_call['function']["name"])
                    parameters = dict(tool_call['function']["arguments"])
                    #TODO: 这部分有问题,需要debug
                    if function_name:
                        server_result = await client.call_tool(function_name, parameters)
                    if server_result:
                        result.append(str(server_result[0].text))
            else:
                return []
            return result
    return []



if __name__ == "__main__":
    print("")
